/**
 * Copyright @ 2000 ysten Co. Ltd. 
 * All right reserved.     
 * @author: wangmin
 * date: 2016-05-15     
 */
package com.task.service.impl;

import com.task.bean.Constants;
import com.task.bean.EnumConstants;
import com.task.entity.ParentTask;
import com.task.repository.IParentTaskRepository;
import com.task.service.IParentTaskService;
import com.task.utils.DateTimeUtils;
import com.task.utils.PageUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 主任务服务
 */
@Service
public class ParentTaskServiceImpl implements IParentTaskService {

    public static final String YYYY_M_MDD = "yyyyMMdd";
    @Autowired
    IParentTaskRepository parentTaskRepository;

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private static final Logger LOGGER = LoggerFactory.getLogger(ParentTaskServiceImpl.class);


    @Override
    public void save(ParentTask parentTask) {
        Lock writeLock = lock.writeLock();
        try {
            writeLock.lock();//加锁
            parentTask.setCode(getParentTaskCode(parentTask.getTaskType()));//设置主任务编码
            parentTaskRepository.save(parentTask);
        } catch (Exception e) {
            LOGGER.error("save parentTask error {}", e);
        } finally {
            writeLock.unlock();
        }
    }

    @Override
    public void delete(Long id) {
        parentTaskRepository.delete(id);
    }

    @Override
    public ParentTask findById(Long id) {
        ParentTask parentTask = parentTaskRepository.findOne(id);
        if (parentTask != null) {
            if (parentTask.getReward() != null) {
                parentTask.setRewardName("¥" + parentTask.getReward());
            } else {
                parentTask.setRewardName(Constants.FREE);
            }
            return parentTask;
        }
        return null;
    }

    @Override
    public Page<ParentTask> findParentTaskPage(Map<String, Object> searchParams, int page, int rows) {
        PageRequest pageRequest = PageUtil.buildPageRequest(page, rows, Constants.DESC, Constants.ID);
        Specification<ParentTask> spec = PageUtil.buildSpecification(searchParams, ParentTask.class);
        return parentTaskRepository.findAll(spec, pageRequest);
    }

    @Override
    public List<ParentTask> findByCondition(Map<String, Object> searchParams) {
        Specification<ParentTask> spec = PageUtil.buildSpecification(searchParams, ParentTask.class);
        return parentTaskRepository.findAll(spec);
    }

    @Override
    public Page<ParentTask> findTaskList(Map<String, Object> searchParams, int page, int rows, String orderBy) {
        PageRequest pageRequest = PageUtil.buildPageRequest(page, rows, Constants.DESC, orderBy);
        Specification<ParentTask> spec = PageUtil.buildSpecification(searchParams, ParentTask.class);
        return parentTaskRepository.findAll(spec, pageRequest);
    }

    @Override
    public String getParentTaskCode(EnumConstants.TaskType taskType) {
        String date = DateTimeUtils.formatCurrentDate(YYYY_M_MDD);
        String code = "";
        if (taskType == EnumConstants.TaskType.DATA) {
            code = "D" + date;
        } else if (taskType == EnumConstants.TaskType.INVEST) {
            code = "M" + date;
        } else if (taskType == EnumConstants.TaskType.ARRANG) {
            code = "T" + date;
        } else if (taskType == EnumConstants.TaskType.PROMOTION) {
            code = "S" + date;
        }
        if (StringUtils.isNotBlank(code)) {
            String maxCode = parentTaskRepository.findMaxCodeByCode(code);//D20160601001
            String newCode = "";
            if (StringUtils.isNotBlank(maxCode)) {
                Integer maxValue = Integer.valueOf(StringUtils.substring(maxCode, 9));
                if (maxValue > 0 && maxValue < 9) {
                    newCode = "00" + (++maxValue);
                }
                if (maxValue >= 9 && maxValue < 99) {
                    newCode = "0" + (++maxValue);
                }
                if (maxValue >= 99) {
                    newCode = "" + (++maxValue);
                }
                return code + newCode;
            } else {
                newCode = "001";
                return code + newCode;
            }
        }
        return "";
    }

/*    public static void main(String[] args) {
        System.out.println(StringUtils.substring("D20160601001", 9));
        Integer maxValue = Integer.valueOf(StringUtils.substring("D20160601001", 9));
        String newCode = "00" + (++maxValue);
        System.out.println(maxValue);
        System.out.println(newCode);
    }*/

}
